﻿using System;

namespace AppConfigVerifier
{
	public class LocalContext : IExtensibleObject
	{
		readonly TypeToken typeToken;
		readonly ExtensionRepository extensions;

		public LocalContext(TypeToken typeToken, GlobalInfo globalInfo)
		{
			this.globalInfo = globalInfo;
			this.typeToken = typeToken;
			log = new Logger<LocalContext>(this, typeToken.TypeName);
			log.LogReceived += OnLogReceived;
			extensions = new ExtensionRepository(this);
		}

		void OnLogReceived(LocalContext sender, 
			Location startLocation, Location endLocation, string message, LogType type)
		{
			Location globalStartLocation = GetFileLocation(startLocation);
			Location globalEndLocation = GetFileLocation(endLocation);
			globalInfo.Log.Send(message, globalStartLocation, globalEndLocation, type);
		}

		readonly Logger<LocalContext> log;

		public Logger<LocalContext> Log
		{
			get
			{
				return log;
			}
		}
        
		readonly GlobalInfo globalInfo;

		public GlobalInfo GlobalInfo
		{
			get
			{
				return globalInfo;
			}
		}

		public TypeToken Token
		{
			get
			{
				return typeToken;
			}
		}

		public String TypeName
		{
			get
			{
				return typeToken.TypeName;
			}
		}
        
		Location GetFileLocation(Location localLocation)
		{
			Location fileLocation;
			if (localLocation.Line == 0)
			{
				fileLocation = new Location(
					typeToken.Location.Line, 
					typeToken.Location.Column + localLocation.Column);
			}
			else
			{
				fileLocation = new Location(
					typeToken.Location.Line + localLocation.Line, 
					localLocation.Column);
			}
			return fileLocation;
		}

		public T GetExtension<T>()
		{
			return extensions.GetExtension<T>();
		}
	}
}
